import React, { useState, useEffect } from 'react';
import { Layout, Menu, Dropdown, Avatar, notification } from 'antd';
import { useNavigate } from 'react-router-dom';
import { UserOutlined } from '@ant-design/icons';
import Management from './management/management';
import Settings from './settings/settings';
import Tools from './tools/tools';
import HomePage from './home_page';
import ChartPage from './chart_page';
import { fetchApi } from '../general/api'; // 根据实际路径调整

const { Header, Content, Footer } = Layout;

interface MenuItem {
    key: string;
    label: string;
}

const NavPage: React.FC = () => {
    const [current, setCurrent] = useState('home');
    const [menuItems, setMenuItems] = useState<MenuItem[]>([]);
    const navigate = useNavigate();

    const [contentHeight, setContentHeight] = useState(window.innerHeight - 130); // 动态计算内容高度
    const updateHeight = () => {
        setContentHeight(window.innerHeight - 150); // 减去 Header 高度
    };
    useEffect(() => {
        window.addEventListener('resize', updateHeight);

        return () => {
            window.removeEventListener('resize', updateHeight);
        };
    }, []);

    const fetchMenuData = async () => {
        console.log('请求菜单数据...'); // 调试日志
        try {
            const data = await fetchApi('/easymonitor/api/menu'); // 使用 fetchApi
            notification.success({
                message: '请求成功',
                description: '菜单数据已成功加载。',
                duration: 2, // 2秒后自动关闭
            });
            setMenuItems(data);
        } catch (error) {
            console.error('获取菜单数据失败:', error);
        }
    };

    useEffect(() => {
        fetchMenuData();
    }, []);

    const handleLogout = () => {
        localStorage.removeItem('token');
        navigate('/');
    };

    const handleMenuClick = (e: any) => {
        setCurrent(e.key);
        navigate(`/${e.key}`);
    };

    // 将 menuItems 转换为适合 items 属性的格式
    const menuItemsForAntd = menuItems.map((item) => ({
        key: item.key,
        label: item.label,
    }));

    // 头像下拉菜单
    const dropdownItems = [
        {
            key: 'logout',
            label: (
                <button
                    onClick={handleLogout}
                    style={{ color: 'red', background: 'none', border: 'none', cursor: 'pointer' }}
                    aria-label="登出" // 增加可访问性标签  
                >
                    登出
                </button>
            ),
        },
    ];

    return (
        <Layout>
            <Header style={{ background: '#fff', padding: 0 }}>
                <div
                    style={{ paddingRight: 20, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}
                >
                    <Menu
                        mode="horizontal"
                        selectedKeys={[current]}
                        onClick={handleMenuClick}
                        items={menuItemsForAntd} // 使用 items 属性
                        style={{ flex: 1 }}
                    />
                    <Dropdown
                        menu={{
                            items: dropdownItems,
                        }} // 替换为新方式
                        trigger={['click']}
                        placement="bottomRight"
                    >
                        <Avatar
                            style={{ backgroundColor: '#87d068', cursor: 'pointer' }}
                            icon={<UserOutlined />}
                        />
                    </Dropdown>
                </div>
            </Header>
            <Content style={{ padding: '20px', height: `${contentHeight}px` }}>
                {current === 'home' && <HomePage />}
                {current === 'chart' && <ChartPage />}
                {current === 'management' && <Management />}
                {current === 'settings' && <Settings />}
                {current === 'tools' && <Tools />}
            </Content>
            <Footer style={{ textAlign: 'center' }}>
                Ant Design ©{new Date().getFullYear()} Created by Ant UED
            </Footer>
        </Layout>
    );
};

export default NavPage;